package ee.ut.maxorato_macobo.oop.mud.network;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class NetEventHandler extends SimpleChannelUpstreamHandler {
	@Override
	public void channelConnected(ChannelHandlerContext context, ChannelStateEvent event) {
		NetSession session = new NetSession(context.getChannel());
		context.setAttachment(session);
		NetEventQueue.add(new NetSessionEvent(session, NetSessionEvent.SessEventType.OPEN, null));
	}
	
	@Override
	public void channelDisconnected(ChannelHandlerContext context, ChannelStateEvent event) {
		NetSession session = (NetSession)context.getAttachment();
		NetEventQueue.add(new NetSessionEvent(session, NetSessionEvent.SessEventType.CLOSE, null));
	}
	
	@Override
	public void messageReceived(ChannelHandlerContext context, MessageEvent event) {
		NetSession session = (NetSession)context.getAttachment();
		NetEventQueue.add(new NetSessionEvent(session, NetSessionEvent.SessEventType.MESSAGE, (String)event.getMessage()));
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext context, ExceptionEvent exception) {
		if(exception.getCause() instanceof ClosedChannelException ||
				exception.getCause() instanceof IOException) {
			
		}
		else {
			exception.getCause().printStackTrace();
		}
	}
}
